package com.coderfans.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ${fanchunshuai} on 2016-9-22.
 *
 * @version: V1.0
 * @Desc: redis 单机版配置
 * @Copyright (c) 2016 58到家-版权所有
 */
public class RedisConfig {
    //redis服务器的ip
    private static String JEDIS_HOST = "";

    //Redis的端口号
    private static int PORT = 6379;

    //可用连接实例的最大数目，默认值为8；
    //如果赋值为-1，则表示不限制；
    // 如果pool已经分配了maxActive个jedis实例，
    // 则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;


    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
    private static int MAX_IDLE = 200;

    //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时，如果
    //超出等待时间则抛出JedisConnectionException
    private static int MAX_WAIT = 10000;

    private static int TIMEOUT = 10000;

    //在borrow一个jedis实例时，是否提前进行validate操作，如果为true,则得到的jedis实例均是可用的
    private static boolean TEST_ON_BORROW = true;

    /**
     * 声明单机版本的redis连接池
     */
    private static JedisPool jedisPool = null;
    private static ShardedJedisPool shardedJedisPool = null;

    /**
     * 生成jedis池
     */
    public synchronized static JedisPool generatJedisPool(){
        if(jedisPool == null){
            try {
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxIdle(MAX_IDLE);
                config.setMaxWaitMillis(MAX_WAIT);
                config.setTestOnBorrow(TEST_ON_BORROW);
                jedisPool = new JedisPool(config,JEDIS_HOST,PORT,TIMEOUT);
                return jedisPool;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jedisPool;
    }




    /**
     * 获取jedis实例
     * @return
     */
    public synchronized static Jedis getJedis(){
        try {
            if(jedisPool!=null){
                Jedis resource = jedisPool.getResource();
                return resource;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成shardedJedis池
     * @param serverInfo
     * @return
     */
    public synchronized  ShardedJedisPool getShardedJedisPool(String serverInfo){
        if(shardedJedisPool != null){
            return shardedJedisPool;
        }else {
            List<JedisShardInfo> jedisShardInfoList = new ArrayList<>();
            String [] serverArray = serverInfo.split(",");
            for (int i = 0 ;i < serverArray.length;i++ ){
                String[] serverBasic = serverArray[i].split(":");
                String host = serverBasic[0];
                int port = Integer.parseInt(serverBasic[1]);
                JedisShardInfo jedisShardInfo = new JedisShardInfo(host,port);
            }
            ShardedJedisPool shardedJedisPool = new ShardedJedisPool(new GenericObjectPoolConfig(),jedisShardInfoList);
            return shardedJedisPool;
        }
    }

}
